package com.ants.modules.articleLable.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.ants.common.annotation.AutoLog;
import com.ants.common.system.query.QueryGenerator;
import com.ants.common.system.result.Result;
import com.ants.modules.articleLable.entity.ArticleLable;
import com.ants.modules.articleLable.service.ArticleLableService;
import com.ants.modules.articleLable.vo.ArticleLableVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 * Author Chen
 * Date   2021/9/7 18:44
 */

@Slf4j
@Api(tags = "标签管理")
@RestController
@RequestMapping("/articleLable")
public class ArticleLableController {

    @Autowired
    ArticleLableService articleLableService;

    @AutoLog(value = "标签管理-列表")
    @ApiOperation(value = "标签管理-列表", notes = "标签管理-列表")
    @GetMapping("/list")
    public Result<?> queryPageList(ArticleLable articleLable,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String username = StpUtil.getLoginIdAsString();
        QueryWrapper<ArticleLable> queryWrapper = QueryGenerator.initQueryWrapper(articleLable, req.getParameterMap());
        queryWrapper.eq("create_by", username);
        queryWrapper.orderByAsc("sort_no");
        Page<ArticleLable> page = new Page<ArticleLable>(pageNo, pageSize);
        IPage<ArticleLable> pageList = articleLableService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param articleLable
     * @return
     */
    @AutoLog(value = "标签管理-添加")
    @ApiOperation(value = "标签管理-添加", notes = "标签管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ArticleLable articleLable) {
        String username = StpUtil.getLoginIdAsString();
        LambdaQueryWrapper<ArticleLable> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ArticleLable::getCreateBy, username);
        long count = articleLableService.count(lqw);
        if (count >= 5) {
            return Result.error("每个人只能自定义5个标签！");
        }
        List<ArticleLable> list = articleLableService.list();
        List<String> nameList = list.stream().map(ArticleLable::getName).collect(Collectors.toList());
        String lowerName = articleLable.getName().toLowerCase().replaceAll(" ", "");
        for (String name : nameList) {
            name = name.toLowerCase().replaceAll(" ", "");
            if (lowerName.equals(name)) {
                return Result.error("标签已存在，或者存在类似标签！");
            }
        }

        if (articleLable.getSortNo() == null) {
            QueryWrapper<ArticleLable> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("max(sort_no) sortNo");
            ArticleLable one = articleLableService.getOne(queryWrapper);
            articleLable.setSortNo(one.getSortNo() + 1);
        }
        articleLableService.save(articleLable);
        return Result.ok("添加成功！");
    }

    @AutoLog(value = "标签管理-添加")
    @ApiOperation(value = "标签管理-添加", notes = "标签管理-添加")
    @PostMapping(value = "/addLable")
    public Result<?> addLable(@RequestBody ArticleLable articleLable) {
        String username = StpUtil.getLoginIdAsString();
        LambdaQueryWrapper<ArticleLable> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ArticleLable::getCreateBy, username);
        long count = articleLableService.count(lqw);
        if (count >= 5) {
            return Result.error("每个人只能自定义5个标签！");
        }
        List<ArticleLable> list = articleLableService.list();
        List<String> nameList = list.stream().map(ArticleLable::getName).collect(Collectors.toList());
        String lowerName = articleLable.getName().toLowerCase().replaceAll(" ", "");
        for (String name : nameList) {
            name = name.toLowerCase().replaceAll(" ", "");
            if (lowerName.equals(name)) {
                return Result.error("标签已存在，或者存在类似标签！");
            }
        }
        QueryWrapper<ArticleLable> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.select("max(sort_no) sortNo");
        ArticleLable one = articleLableService.getOne(queryWrapper2);
        articleLable.setSortNo(one.getSortNo() + 1);
        articleLableService.save(articleLable);
        ArticleLableVo articleLableVo = new ArticleLableVo();
        articleLableVo.setKey(articleLable.getId());
        articleLableVo.setLabel(articleLable.getName());
        return Result.ok(articleLableVo);
    }

    /**
     * 编辑
     *
     * @param articleLable
     * @return
     */
    @AutoLog(value = "标签管理-编辑")
    @ApiOperation(value = "标签管理-编辑", notes = "标签管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ArticleLable articleLable) {
        articleLableService.updateById(articleLable);
        return Result.ok("编辑成功!");
    }

    /**
     * @param id
     * @return
     * @功能：删除
     */
    @AutoLog(value = "标签管理-删除")
    @ApiOperation(value = "标签管理-删除", notes = "标签管理-删除")
    @DeleteMapping("/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        boolean ok = articleLableService.removeById(id);
        if (ok) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

    /**
     * @param ids
     * @return
     * @功能：批量删除
     */
    @AutoLog(value = "标签管理-批量删除")
    @ApiOperation(value = "标签管理-批量删除", notes = "标签管理-批量删除")
    @DeleteMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        boolean ok = articleLableService.removeByIds(Arrays.asList(ids.split(",")));
        if (ok) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }


    @AutoLog(value = "标签管理-根据用户查询标签")
    @ApiOperation(value = "标签管理-根据用户查询标签", notes = "标签管理-根据用户查询标签")
    @GetMapping("/genArticleLableList")
    public Result<?> genArticleLableList(@RequestParam(required = false) String name) {
        String username = StpUtil.getLoginIdAsString();
        LambdaQueryWrapper<ArticleLable> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ArticleLable::getCreateBy, username);

        lqw.orderByAsc(ArticleLable::getSortNo);

        List<ArticleLable> list = articleLableService.list(lqw);

        List<ArticleLableVo> articleLableVoList = new ArrayList<>();
        ArticleLableVo articleLableVo = null;
        for (ArticleLable articleLable : list) {
            articleLableVo = new ArticleLableVo();
            articleLableVo.setKey(articleLable.getId());
            articleLableVo.setLabel(articleLable.getName());
            articleLableVoList.add(articleLableVo);
        }
        return Result.ok(articleLableVoList);
    }

    @AutoLog(value = "标签管理-查询登陆用户外的所有标签")
    @ApiOperation(value = "标签管理-查询登陆用户外的所有标签", notes = "标签管理-查询登陆用户外的所有标签")
    @GetMapping("/getLableAll")
    public Result<?> getLableAll() {
        String username = StpUtil.getLoginIdAsString();
        LambdaQueryWrapper<ArticleLable> lqw = new LambdaQueryWrapper<>();
        lqw.ne(ArticleLable::getCreateBy, username);

        lqw.orderByAsc(ArticleLable::getSortNo);

        List<ArticleLable> list = articleLableService.list(lqw);

        List<ArticleLableVo> articleLableVoList = new ArrayList<>();
        ArticleLableVo articleLableVo = null;
        for (ArticleLable articleLable : list) {
            articleLableVo = new ArticleLableVo();
            articleLableVo.setKey(articleLable.getId());
            articleLableVo.setLabel(articleLable.getName());
            articleLableVoList.add(articleLableVo);
        }
        return Result.ok(articleLableVoList);
    }

    @AutoLog(value = "标签管理-查询指定标签")
    @ApiOperation(value = "标签管理-查询指定标签", notes = "标签管理-查询指定标签")
    @GetMapping("/getLableById")
    public Result<?> getLableById(@RequestParam String ids) {
        LambdaQueryWrapper<ArticleLable> lqw = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(ids)) {
            lqw.in(ArticleLable::getId, ids.split(","));
        }
        List<ArticleLable> list = articleLableService.list(lqw);

        List<ArticleLableVo> articleLableVoList = new ArrayList<>();
        ArticleLableVo articleLableVo = null;
        for (ArticleLable articleLable : list) {
            articleLableVo = new ArticleLableVo();
            articleLableVo.setKey(articleLable.getId());
            articleLableVo.setLabel(articleLable.getName());
            articleLableVoList.add(articleLableVo);
        }
        return Result.ok(articleLableVoList);
    }


}
